package main

import (
	"github.com/go-co-op/gocron"
	"os"
	"parking/src/structs"
	"path/filepath"
	"time"
)

// 图片本地存储结构体管道
var localStorePictureChan = make(chan *structs.LocalStorePictureStruct, 15)

func init() {
	go localStorePictureTask(localStorePictureChan)
	go localCleanPictureTask(localStorePath, 1*time.Hour, 1, "15:51")
}

// pictureDir:目标文件夹的绝对路径   timeDuration:过期时间长度   interval:执行周期(日)   executeTime:执行时间
func localCleanPictureTask(pictureDir string, timeDuration time.Duration, interval int, executeTime string) {
	// 过期时间
	cutoffTime := time.Now().Add(-timeDuration)
	// 创建一个新的 Scheduler 实例
	scheduler := gocron.NewScheduler(time.Local)
	_, err := scheduler.
		Every(interval).
		Day().
		At(executeTime).
		Do(func() { //本地图片删除逻辑
			// 整理图片信息集合
			entries, err := os.ReadDir(pictureDir)
			if err != nil {
				logger.Error("定时任务清除本地图片时读取图片信息集合失败", err)
				return
			}
			var count = 0
			for _, entry := range entries {
				if entry.IsDir() {
					continue // 跳过目录
				}
				filePath := filepath.Join(pictureDir, entry.Name())
				fileInfo, err := entry.Info()
				if err != nil {
					logger.Error("定时任务清除本地图片时获取某个图片信息失败", err)
					continue
				}
				// 筛选过期图片并删除
				if fileInfo.ModTime().Before(cutoffTime) {
					err := os.Remove(filePath)
					if err != nil {
						logger.Error("定时任务清除本地图片时删除某个图片失败", err)
					} else {
						count++
						logger.Infof("定时任务清除本地图片 Deleted file: %s", filePath)
					}
				}
			}
			logger.Infof("定时任务清除本地图片 清除: %v 张", count)
		})
	if err != nil {
		logger.Fatal("清除本地照片定时任务注册失败", err)
	}
	// 启动调度器
	scheduler.StartAsync()
	logger.Infof("本地图片删除定时任务启动成功,过期期限: 超过%v 执行周期: %v天 执行时间: %v", timeDuration, interval, executeTime)
}

// 图片本地存储协程任务
func localStorePictureTask(localStorePictureChan chan *structs.LocalStorePictureStruct) {
	logger.Infof("图片本地存储协程任务启动成功")
	for LocalStorePictureStruct := range localStorePictureChan {
		// 创建文件
		file, err := os.Create(LocalStorePictureStruct.GetAbsolutePath())
		if err != nil {
			logger.Fatal("Error creating file", err)
		}
		// 写入数据
		_, err = file.Write(LocalStorePictureStruct.GetPicData())
		if err != nil {
			logger.Fatal("Error Write file", err)
		}
		err = file.Close()
		if err != nil {
			logger.Error("Error Close IO", err)
		} else {
			logger.Infof("图片本地存储成功,文件路径: %v", LocalStorePictureStruct.GetAbsolutePath())
		}
	}
}
